<template>
  <el-dialog
    title="选择管道预警"
    :visible.sync="visible"
    width="60%"
    @close="handleClose"
  >
    <!-- 搜索区域 -->
    <div class="pipe-warning-container">
      <div class="search-action-bar">
        <el-form :model="searchForm" inline class="search-form">
          <el-form-item label="预警名称">
            <el-input
              v-model="searchForm.warName"
              placeholder="请输入预警名称"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="warning" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格区域（修复单选选中状态） -->
      <el-table
        :data="tableData"
        style="width: 100%"
        max-height="400"
        border
        stripe
        @selection-change="handleSelectionChange" 
        :row-key="(row) => row.pipeWarId"
        ref="warningTable" 
      >
        <!-- 单选勾选框 -->
        <el-table-column
          type="selection"
          width="55"
          :selectable="() => true" 
        />
        <el-table-column prop="pipeWarId" label="预警管理ID" />
        <el-table-column prop="warName" label="预警名称" />
        <el-table-column prop="warPercent" label="预警百分比" />
        <el-table-column
          prop="updateTime"
          label="更新时间"
          :formatter="formatDate"
        />
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination-bar" style="margin-top: 10px">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageDto.page"
          :page-sizes="[5, 10, 20]"
          :page-size="pageDto.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        />
      </div>

      <!-- 确认/取消按钮（修复禁用逻辑） -->
      <div style="text-align: right; margin-top: 10px">
        <el-button type="danger" @click="handleClose">取消</el-button>
        <el-button
          type="success"
          @click="confirmSelect"
          :disabled="selectedRows.length !== 1" 
        >
          确认选择
        </el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: 'PipeWarningSelector',
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      searchForm: {}, 
      pageDto: { page: 1, size: 10, pipeWarning: {} }, 
      total: 0, 
      tableData: [], 
      selectedRows: [], 
      historyIds: JSON.parse(localStorage.getItem('pipeWarHistoryIds')) || [] 
    };
  },
  methods: {
    formatDate(row, column) {
      const date = row[column.property];
      return date ? new Date(date).toLocaleString() : '';
    },
    handleSizeChange(val) {
      this.pageDto.size = val;
      this.queryByPage();
    },
    handleCurrentChange(val) {
      this.pageDto.page = val;
      this.queryByPage();
    },
    handleQuery() {
      this.pageDto.pipeWarning.warName = this.searchForm.warName;
      this.pageDto.page = 1; 
      this.queryByPage();
    },
    resetQuery() {
      this.searchForm = {};
      this.pageDto = { page: 1, size: 10, pipeWarning: {} };
      this.queryByPage();
    },
    queryByPage() {
      this.$api.pipeWarningApi
        .queryByPage(this.pageDto)
        .then((res) => {
          if (res.data.code === 1) {
            this.tableData = res.data.data.list;
            this.total = res.data.data.total;
          } else {
            this.$notify.error({
              title: '错误',
              message: res.data.msg || '查询失败'
            });
          }
        })
        .catch(() => {
          this.$notify.error({
            title: '错误',
            message: '网络异常，请重试'
          });
        });
    },
    // 关键：表格多选事件，实时更新选中行
    handleSelectionChange(val) {
      this.selectedRows = val;
    },
    confirmSelect() {
      if (this.selectedRows.length !== 1) {
        this.$notify.warning({
          title: '提示',
          message: '请选择**一条**数据'
        });
        return;
      }
      const selectedRow = this.selectedRows[0];
      this.$emit('selected', selectedRow.pipeWarId, selectedRow.warName);
      if (!this.historyIds.includes(selectedRow.pipeWarId)) {
        this.historyIds.push(selectedRow.pipeWarId);
        localStorage.setItem('pipeWarHistoryIds', JSON.stringify(this.historyIds));
      }
      this.handleClose();
    },
    handleClose() {
      this.selectedRows = [];
      this.$refs.warningTable.clearSelection(); 
      this.$emit('update:visible', false);
    }
  },
  watch: {
    visible(newVal) {
      if (newVal) {
        this.queryByPage();
      }
    }
  }
};
</script>

<style scoped>
.pipe-warning-container {
  padding: 10px;
}
</style>